package cn.com.sealevel.client;

import cn.com.sealevel.bean.CborBean;
import cn.com.sealevel.main.Main;
import cn.com.sealevel.util.CborUtil;
import cn.com.sealevel.util.ConfigUtil;
import cn.com.sealevel.util.DataFileWriter;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.mqtt.MqttConnectReturnCode;
import io.netty.handler.codec.mqtt.MqttVersion;

import java.nio.charset.StandardCharsets;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.lang3.time.FastDateFormat;
import org.jetlinks.mqtt.client.MqttClient;
import org.jetlinks.mqtt.client.MqttClientCallback;
import org.jetlinks.mqtt.client.MqttClientImpl;
import org.jetlinks.mqtt.client.MqttConnectResult;
import org.jetlinks.mqtt.client.MqttHandler;
import org.jetlinks.mqtt.client.MqttHandlerImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/* loaded from: netty-mqtt-client-1.0.0.jar:cn/com/sealevel/client/Terminal.class */
public class Terminal {
    private EventLoopGroup workerGroup;
    private String clientId;
    private String username;
    private String password;
    public int connectDelayInMillis;
    public int sendDataCount;
    private DataFileWriter writer;
    private StringBuilder data;
    private static final Logger logger = LoggerFactory.getLogger(Terminal.class);
    private static FastDateFormat formatter = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss.SSS");
    private static DecimalFormat lonFormat = new DecimalFormat("00000.0000");
    private static DecimalFormat latFormat = new DecimalFormat("0000.0000");
    private static SimpleDateFormat YYMMDD = new SimpleDateFormat("yyMMdd");
    private static SimpleDateFormat HHMMSS = new SimpleDateFormat("HHmmss.SSS");
    private MqttClient mqttClient = null;
    private final Random random = new Random();
    private int seed = this.random.nextInt(4);
    private AtomicInteger seq = new AtomicInteger(0);
    private Integer sentNum = 0;
    private Boolean status = true;
    private Boolean needSave = false;
    private volatile Boolean isStop = false;
    private double lon = (((double) this.random.nextInt(24000000)) + 9.1E7d) / 10000.0d;
    private double lat = ((double) (this.random.nextInt(12000000) + 29000000)) / 10000.0d;

    private String json = "{\n" +
            "  \"SquareCover\": {\n" +
            "    \"QRCode\": \"ALPTA-6671EC140124092615111709\",\n" +
            "    \"productType\": 0,\n" +
            "    \"deviceCode\": \"line-014\",\n" +
            "    \"markingTime\": \"2024/9/26 15:50:40\",\n" +
            "    \"markingPower\": \"47\",\n" +
            "    \"MarkSpeed\": \"2900\",\n" +
            "    \"grade\": \"B\",\n" +
            "    \"weldingResultsOfValve\": \"OK\",\n" +
            "    \"valvePower\": \"45\",\n" +
            "    \"valveSpeed\": \"100\",\n" +
            "    \"valveZAxisHeight\": \"24.5\",\n" +
            "    \"weldPosiPolePowerRatio\": \"50\",\n" +
            "    \"weldPosiPolePower\": \"\",\n" +
            "    \"weldPosiPoleSpeed\": \"90\",\n" +
            "    \"weldPosiPoleZAxisHeight\": \"454\",\n" +
            "    \"weldPosiPolePressure\": \"87.2\",\n" +
            "    \"weldNegPolePowerRatio\": \"50\",\n" +
            "    \"weldNegPolePower\": \"\",\n" +
            "    \"weldNegPoleSpeed\": \"90\",\n" +
            "    \"weldNegPoleZAxisHeight\": \"455\",\n" +
            "    \"weldNegPolePressure\": \"81.5\",\n" +
            "    \"weldResultsOfPole\": \"OK\",\n" +
            "    \"metalWireResults\": \"OK\",\n" +
            "    \"posiElectrode16_1\": \"1.954\",\n" +
            "    \"posiElectrode16_2\": \"1.956\",\n" +
            "    \"posiElectrode16_3\": \"1.928\",\n" +
            "    \"posiElectrode16_4\": \"1.939\",\n" +
            "    \"posiElectrode16_Result\": \"OK\",\n" +
            "    \"negElectrode16_1\": \"1.963\",\n" +
            "    \"negElectrode16_2\": \"1.958\",\n" +
            "    \"negElectrode16_3\": \"1.96\",\n" +
            "    \"negElectrode16_4\": \"1.935\",\n" +
            "    \"negElectrode16_Result\": \"OK\",\n" +
            "    \"posiElectrode32_1\": \"3.444\",\n" +
            "    \"posiElectrode32_2\": \"3.463\",\n" +
            "    \"posiElectrode32_3\": \"3.466\",\n" +
            "    \"posiElectrode32_4\": \"3.528\",\n" +
            "    \"posiElectrode32_Result\": \"OK\",\n" +
            "    \"negElectrode32_1\": \"3.471\",\n" +
            "    \"negElectrode32_2\": \"3.531\",\n" +
            "    \"negElectrode32_3\": \"3.46\",\n" +
            "    \"negElectrode32_4\": \"3.516\",\n" +
            "    \"negElectrode32_Result\": \"OK\",\n" +
            "    \"lowerPlasticAmplitude\": \"50\",\n" +
            "    \"lowerPlasticEnergy\": \"110\",\n" +
            "    \"lowerPlasticPressure\": \"400\",\n" +
            "    \"hotMeltResult\": \"OK\",\n" +
            "    \"heliumResults\": \"OK\",\n" +
            "    \"chamberInitPressure\": \"150.3\",\n" +
            "    \"chamberInitTime\": \"1\",\n" +
            "    \"ReChamberPressure\": \"\",\n" +
            "    \"ReChamberTime\": \"\",\n" +
            "    \"HDPositivePressure\": \"\",\n" +
            "    \"HDNegativePressure\": \"\",\n" +
            "    \"HDInitLeakRate\": \"7.739585E-09\",\n" +
            "    \"HDReLeakRate\": \"\",\n" +
            "    \"heFirstResult\": \"OK\",\n" +
            "    \"heSecondResult\": \"\",\n" +
            "    \"positInsuVol\": \"1.037\",\n" +
            "    \"positInsuRes\": \"99.900002\",\n" +
            "    \"positInsuTime\": \"0\",\n" +
            "    \"PosiCurrentVol\": \"1.523\",\n" +
            "    \"PosiCurrentCur\": \"0\",\n" +
            "    \"PosiCurrentTime\": \"0\",\n" +
            "    \"negInsuVol\": \"1.037\",\n" +
            "    \"negInsuRes\": \"99.900002\",\n" +
            "    \"negInsuTime\": \"0\",\n" +
            "    \"negCurVol\": \"1.503\",\n" +
            "    \"negCurRes\": \"0.0003\",\n" +
            "    \"negCurTime\": \"0\",\n" +
            "    \"posiCircResult\": \"OK\",\n" +
            "    \"negCircResult\": \"OK\",\n" +
            "    \"elecTestResults\": \"OK\",\n" +
            "    \"flatness\": \"0.233\",\n" +
            "    \"flatnessResult\": \"OK\",\n" +
            "    \"filmAppResults\": \"OK\"\n" +
            "  }\n" +
            "}";

    public Terminal(EventLoopGroup workerGroup, String clientId, String username, String password, int connectDelayInMillis, int sendDataCount) {
        this.workerGroup = workerGroup;
        this.clientId = clientId;
        this.username = username;
        this.password = password;
        this.connectDelayInMillis = connectDelayInMillis;
        this.sendDataCount = sendDataCount;
    }

    public void connect() {
        try {
            MqttHandler handler = new MqttHandlerImpl();
            this.mqttClient = new MqttClientImpl(handler);
            this.mqttClient.setEventLoop(this.workerGroup);
            this.mqttClient.getClientConfig().setChannelClass(NioSocketChannel.class);
            this.mqttClient.getClientConfig().setClientId(this.clientId);
            this.mqttClient.getClientConfig().setUsername(this.username);
            this.mqttClient.getClientConfig().setPassword(this.password);
            this.mqttClient.getClientConfig().setProtocolVersion(MqttVersion.MQTT_3_1_1);
            this.mqttClient.getClientConfig().setReconnect(false);
//            this.mqttClient.on(ConfigUtil.subTimeTopic, handler);
            this.mqttClient.setCallback(new MqttClientCallback() { // from class: cn.com.sealevel.client.Terminal.1
                @Override // org.jetlinks.mqtt.client.MqttClientCallback
                public void connectionLost(Throwable cause) {
                    Terminal.logger.error("connectionLost exception:" + Terminal.this.clientId, cause);
                }

                @Override // org.jetlinks.mqtt.client.MqttClientCallback
                public void onSuccessfulReconnect() {
                }
            });
            this.mqttClient.connect(ConfigUtil.ip, ConfigUtil.port).addListener(future -> {
                try {
                    MqttConnectResult result = (MqttConnectResult) future.get(5, TimeUnit.SECONDS);
                    if (result.getReturnCode() != MqttConnectReturnCode.CONNECTION_ACCEPTED) {
                        logger.error("connect error:" + this.clientId + "," + result.getReturnCode());
                        this.mqttClient.disconnect();
                    } else {
                        logger.info("connect success:" + this.clientId);
                        beginDataTask();
                    }
                } catch (Exception e) {
                    logger.error("connect exception:" + this.clientId, e);
                }
            });
        } catch (Exception e) {
            logger.error("connect exception:" + this.clientId, e);
        }
    }

    public void start() {
        this.workerGroup.schedule(new Runnable() { // from class: cn.com.sealevel.client.Terminal.2
            @Override // java.lang.Runnable
            public void run() {
                Terminal.this.connect();
            }
        }, this.connectDelayInMillis, TimeUnit.MILLISECONDS);
        if (this.needSave) {
            this.writer = new DataFileWriter(this.clientId + ".data");
            this.writer.write("TIME,MESSAGE\n");
        }
    }

    public void stop() {
        if (!this.isStop) {
            this.isStop = true;
            logger.info("Terminal[{}] channel closing. count[{}]", this.clientId, this.sentNum);
            Main.latch.countDown();
            logger.info("Terminal Last:[{}]", Main.latch.getCount());
            this.mqttClient.disconnect();
            if (this.needSave) {
                this.writer.close();
            }
            if (this.sentNum < this.sendDataCount) {
                this.status = false;
            }
        }
    }

    public void beginDataTask() {
        this.mqttClient.getChannel().eventLoop().schedule(new Runnable() { // from class: cn.com.sealevel.client.Terminal.3
            @Override // java.lang.Runnable
            public void run() {
                Terminal.this.sendData();
            }
        }, 1, TimeUnit.MILLISECONDS);
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void sendData() {
        if (!this.mqttClient.isConnected() || this.sentNum >= this.sendDataCount) {
            this.mqttClient.getChannel().eventLoop().schedule(new Runnable() { // from class: cn.com.sealevel.client.Terminal.6
                @Override // java.lang.Runnable
                public void run() {
                    Terminal.this.stop();
                }
            }, 20, TimeUnit.SECONDS);
            return;
        }
        try {
            this.mqttClient.publish(ConfigUtil.pubRealtimeCborTopic, packData()).addListener(future -> {
                if (!future.isSuccess()) {
                    logger.warn("Terminal[{}] send message failed.", this.clientId);
                    logger.error("send message failed:" + this.clientId, future.cause());
                    this.mqttClient.getChannel().eventLoop().schedule(new Runnable() { // from class: cn.com.sealevel.client.Terminal.4
                        @Override // java.lang.Runnable
                        public void run() {
                            Terminal.this.stop();
                        }
                    }, 20, TimeUnit.SECONDS);
                } else if (this.needSave) {
                    this.writer.write(this.data.toString() + "\n");
                    logger.info("Terminal[{}] send message success.", this.clientId);
                }
            });
            this.mqttClient.getChannel().eventLoop().schedule(new Runnable() { // from class: cn.com.sealevel.client.Terminal.5
                @Override // java.lang.Runnable
                public void run() {
                    Terminal.this.sendData();
                }
            }, ConfigUtil.heartBeatIntervalInMillis, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            logger.error("Heartbeat message error", e);
        }
    }

    public ByteBuf packData() {
        ByteBuf byteBuf = Unpooled.copiedBuffer(json, StandardCharsets.UTF_8);
        long sysTime = System.currentTimeMillis();
        this.sentNum = this.sentNum + 1;
        this.seq.incrementAndGet();
        if (this.needSave) {
            this.data = new StringBuilder();
            this.data.append(formatter.format(sysTime)).append(",");
            this.data.append(json);
        }
        return byteBuf;
    }

    public ByteBuf packData2() {
        long sysTime = System.currentTimeMillis();
        this.sentNum = this.sentNum + 1;
        this.seq.incrementAndGet();
        byte[] message = null;
        CborBean bean = null;
        if (this.seq.get() % 1 == 0) {
            bean = CborUtil.encodeCborData1S();
        }
        if (this.seq.get() % 60 == 0) {
            bean = CborUtil.encodeCborData1Min(getLocation());
        }
        if (this.seq.get() % 180 == 0) {
            bean = CborUtil.encodeCborData3Min(getLocation());
        }
        if (this.seq.get() % 1800 == 0) {
            bean = CborUtil.encodeCborData30Min(getLocation());
        }
        if (this.seq.get() >= 36000) {
            this.seq.set(0);
        }
        if (bean != null) {
            message = bean.getMessage();
            if (this.needSave) {
                this.data = new StringBuilder();
                this.data.append(formatter.format(sysTime)).append(",");
                this.data.append(bean.getData());
            }
        }
        return Unpooled.wrappedBuffer(message);
    }

    public int getSentNum() {
        return this.sentNum;
    }

    public String getClientId() {
        return this.clientId;
    }

    public void setStatus(Boolean status) {
        this.status = status;
    }

    public Boolean getStatus() {
        return this.status;
    }

    public Boolean getNeedSave() {
        return this.needSave;
    }

    public void setNeedSave(Boolean needSave) {
        this.needSave = needSave;
    }

    public String getFilePath() {
        return this.writer.getFilePath();
    }

    private String getLocation() {
        Date date = new Date();
        if (this.sentNum / 20 < 10) {
            this.lon += 1.0E-6d;
        } else {
            this.lat += 1.0E-6d;
        }
        return "$GPRMC," + HHMMSS.format(date) + ",A," + latFormat.format(this.lat) + ",N," + lonFormat.format(this.lon) + ",E,0.000,74.11," + YYMMDD.format(date) + ",,,D*49";
    }
}
